/**
 * 
 */
package com.wolfpire.info.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wolfpire.info.dao.SchoolServiceInfoDao;
import com.wolfpire.info.model.SchoolServiceInfo;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;

/**
 * @author lihd
 *
 */

@Repository("schoolServiceInfoDao")
public class SchoolServiceInfoDaoImpl extends
		BaseHibernateDao<SchoolServiceInfo, Long> implements
		SchoolServiceInfoDao {

	@Override
	public Page<SchoolServiceInfo> findSchoolServiceInfos(
			Page<SchoolServiceInfo> page,
			SchoolServiceInfo filterSchoolServiceInfo) {
		Criterion[] criterions = this.createFilter(filterSchoolServiceInfo);
		int totalCount = this.findIntByCriteria(criterions);
		page.setTotalCount(totalCount);
		
		if (0 < totalCount) {
			Criteria c = this.createCriteria(criterions);
			c.addOrder(Order.desc("year"));
//			c.addOrder(Order.desc("id"));
			c = this.setPageParameter(c, page);
			@SuppressWarnings("unchecked")
			List<SchoolServiceInfo> result = c.list();
			page.setDataList(result);
		}
		return page;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SchoolServiceInfo> list(SchoolServiceInfo schoolServiceInfo) {
		Criterion[] criterions = this.createFilter(schoolServiceInfo);
		Criteria c = this.createCriteria(criterions);
		return c.list();
	}
	
	private Criterion[] createFilter(SchoolServiceInfo filterSchoolServiceInfo) {
		if (null == filterSchoolServiceInfo) {
			return null;
		}
		List<Criterion> criterions = new ArrayList<Criterion>();
		if (null != filterSchoolServiceInfo.getId()) {
			criterions.add(Restrictions.eq("id", filterSchoolServiceInfo.getId()));
		}
		if (!StringUtils.isBlank(filterSchoolServiceInfo.getName())) {
			criterions.add(Restrictions.like("name", filterSchoolServiceInfo.getName(), MatchMode.ANYWHERE));
		}
		if (null != filterSchoolServiceInfo.getYear()) {
			criterions.add(Restrictions.eq("year", filterSchoolServiceInfo.getYear()));
		}
		if (null != filterSchoolServiceInfo.getDelFlag()) {
			criterions.add(Restrictions.eq("delFlag", filterSchoolServiceInfo.getDelFlag()));
		}
		return criterions.toArray(new Criterion[criterions.size()]);
	}
}
